package ru.home.shoppinglist;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class GoodsActivity extends Activity {
	private static final String LOG_TAG = "GoodsActivity";
	private static final int MENU_ADD_GOODS = 0;
	DBHelper dbHelper;
	ListView lvData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_goods);
		dbHelper = new DBHelper(this);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		long catId = getIntent().getLongExtra("category_id", -1);
		Cursor cursor = db
				.rawQuery(
						"select g.id _id,g.name||id name "
								+ " from goods g"
								+ " where _id in (select distinct id from GoodsClassification gc where gc.classification_id="
								+ catId + ")" + " order by name", null);
		startManagingCursor(cursor);
		// формируем столбцы сопоставления
		String[] from = new String[] { "name" };
		int[] to = new int[] { R.id.tvText };

		// registerForContextMenu(findViewById(R.id.lvClassifications));

		SimpleCursorAdapter scAdapter = new SimpleCursorAdapter(this,
				R.layout.goods_item, cursor, from, to);
		lvData = (ListView) findViewById(R.id.lvGoods);
		lvData.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		// android.R.layout.simple_list_item_single_choice
		lvData.setAdapter(scAdapter);
		lvData.setOnCreateContextMenuListener(this);
		lvData.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long id) {

				Log.d(LOG_TAG, id + "");
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.goods, menu);
		menu.add(0, MENU_ADD_GOODS, 0, "Add");
		return true;
	}

	// обработка нажатий
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ADD_GOODS:
			Intent intent = new Intent(this, EditGoodsActivity.class);
			startActivity(intent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
